<!-- 商品分类 -->
<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        class="tree-table"
        :data="cateList"
        :columns="columns"
        :show-index="true"
        :selection-type="false"
        :expand-type="false"
        :show-row-hover="false"
        index-text=""
        border
      >
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level == 0" size="mini">一级</el-tag>
          <el-tag
            type="success"
            v-else-if="scope.row.cat_level == 1"
            size="mini"
            >二级</el-tag
          >
          <el-tag type="warning" v-else size="mini">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showCateDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChanged"
            clearable
            change-
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditDailog"
    >
      <!-- 编辑商品分类表单 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: [],
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      cateList: [], //商品分类列表
      //为table指定列的定义
      columns: [
        { label: "商品分类", prop: "cat_name" },
        { label: "是否有效", type: "template", template: "isOk" },
        { label: "排序", type: "template", template: "order" },
        { label: "操作", type: "template", template: "opt" },
      ],
      addCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //分类名称
        cat_name: "",
        //分类父id
        cat_pid: 0,
        //分类层级,默认一级
        cat_level: 0,
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级分类级联选择器的选项
      parentCateList: [],
      //父级分类级联选择器的配置项
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //父级分类级联选择器的选中项id
      selectedKeys: [],
      //编辑分类对话框的显示与隐藏
      editDialogVisible: false,
      //编辑商品分类表单
      editCateForm: {},
      editCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },

  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status == 200) {
        this.cateList = res.data.result;
        this.total = res.data.total;
      } else {
        this.$message.error("获取商品分类列表失败！");
      }
    },
    //每页展示多少条
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.queryInfo.pagenum = 1;
      this.getCateList();
    },
    //切换到多少页
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getCateList();
    },
    //打开添加分类对话框
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status == 200) {
        this.parentCateList = res.data;
      } else {
        this.$message.error("获取父级分类数据失败！");
      }
    },
    //父级分类选择项改变
    parentCateChanged() {
      this.addCateForm.cat_level = this.selectedKeys.length;
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        this.addCateForm.cat_pid = 0;
      }
      console.log(this.addCateForm);
    },
    //添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status == 201) {
          this.$message.success("添加分类成功！");
          this.getCateList();
          this.addCateDialogVisible = false;
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },
    //添加商品分类对话框关闭时执行
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //显示编辑商品分类对话框
    async showCateDialog(id) {
      const { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status == 200) {
        this.editCateForm = res.data;
        this.editDialogVisible = true;
      } else {
        this.$message.error("获取商品分类信息失败！");
      }
    },
    closeEditDailog() {
      this.$refs.editCateFormRef.resetFields();
    },
    //编辑分类
    editCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/${this.editCateForm.cat_id}`,
            { cat_name: this.editCateForm.cat_name }
          );
          if (res.meta.status == 200) {
            this.$message.success("修改商品分类信息成功！");
            this.getCateList();
            this.editDialogVisible = false;
          } else {
            this.$message.error("修改商品分类信息失败！");
          }
        }
      });
    },
    //删除商品分类
    deleteCate(id) {
      this.$confirm("此操作将永久删除该商品分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/${id}`);
          if (res.meta.status == 200) {
            this.$message.success("商品分类删除成功！");
            this.getCateList();
          } else {
            this.$message.error("商品分类删除失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang='less' scoped>
.tree-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
.el-card {
  min-width: 900px;
  overflow: auto;
}
</style>